package cn.com.egova.permission.szzt.lib;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import cn.com.egova.permission.R;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * 默认对话框，包括标题、进度条、提示文本、输入框、确认和取消按钮
 * <br>
 */
public class CustomDialog extends Dialog {
    private View layoutContainer;
    private TextView tvContent;
    private TextView tvTitle;
    private Button btnOk;
    private Button btnCancel;
    private Button btnNeutral;
    private View progressBar;
    private ViewGroup layoutBtns;
    private EditText etInput;
    private Context mContext;
    private Handler mHandler;

    public CustomDialog(@NonNull Context context) {
        super(context, R.style.g_alert_dialog);
        init(context);
    }

    public CustomDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        init(context);
    }

    protected CustomDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        layoutContainer = LayoutInflater.from(context).inflate(R.layout.g_base_dialog, null);
        tvContent = (TextView) layoutContainer.findViewById(R.id.tv_content);
        tvTitle = (TextView) layoutContainer.findViewById(R.id.tv_title);
        btnCancel = (Button) layoutContainer.findViewById(R.id.btn_cancel);
        btnOk = (Button) layoutContainer.findViewById(R.id.btn_confirm);
        btnNeutral = (Button) layoutContainer.findViewById(R.id.btn_neutral);
        progressBar = layoutContainer.findViewById(R.id.progressbar);
        layoutBtns = (ViewGroup) layoutContainer.findViewById(R.id.layout_buttons);
        etInput = (EditText) layoutContainer.findViewById(R.id.et_input);
        if (getWindow() != null) {
            getWindow().setWindowAnimations(R.style.g_alert_dialog_anim);
        }
        if(mHandler==null){
            mHandler = new Handler(Looper.getMainLooper());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutContainer, new ViewGroup.LayoutParams(getContext()
                .getResources().getDimensionPixelOffset(R.dimen.alert_width),
                WRAP_CONTENT));
    }

    /**
     * 隐藏标题
     */
    public CustomDialog hideTitle() {
        tvTitle.setVisibility(View.GONE);
        return this;
    }

    /**
     * @param title empty时使用默认标题“提示”，考虑到标题一般情况
     *              下都要显示，如果要隐藏使用{@link #hideTitle}
     */
    public CustomDialog showTitle(CharSequence title) {
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(title);
        }
        return this;
    }

    public CustomDialog showTitle(int title) {
        return showTitle(mContext.getString(title));
    }

    /**
     * @see #showTitle(CharSequence)
     */
    @Override
    public void setTitle(@Nullable CharSequence title) {
        showTitle(title);
    }

    /**
     * @see #showTitle(CharSequence)
     */
    @Override
    public void setTitle(@StringRes int titleId) {
        showTitle(mContext.getString(titleId));
    }

    /**
     * @param content 当为empty时隐藏内容，否则显示 类似于@setMessage
     */
    public CustomDialog setContent(String content) {
        if (!TextUtils.isEmpty(content)) {
            tvContent.setVisibility(View.VISIBLE);
            tvContent.setText(content);
        } else {
            tvContent.setVisibility(View.GONE);
        }
        return this;
    }

    public CustomDialog setContent(int content) {
        return setContent(mContext.getString(content));
    }

    public CustomDialog setShowProgressbar(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        return this;
    }

    /**
     * @param listener 为null时不显示确认按钮，使用默认按钮文字“确认”
     */
    public CustomDialog setConfirmButton(final OnClickListener listener) {
        return setConfirmButton(null, listener);
    }

    /**
     * @param listener 为null时不显示确认按钮
     * @param text     为null时使用默认按钮文字
     */
    public CustomDialog setConfirmButton(String text, final OnClickListener listener) {
        configureButton(text, listener, btnOk);
        return this;
    }

    /**
     * @param listener 为null时不显示取消按钮，使用默认按钮文字“取消”
     */
    public CustomDialog setCancelButton(final OnClickListener listener) {
        return setCancelButton(null, listener);
    }

    /**
     * @param listener 为null时不显示取消按钮
     * @param text     为null时使用默认按钮文字
     */
    public CustomDialog setCancelButton(String text, final OnClickListener listener) {
        configureButton(text, listener, btnCancel);
        return this;
    }

    /**
     * @param listener 为null时不显示取消按钮
     * @param text     按钮文字，该按钮没有默认文字
     */
    public CustomDialog setNeutralButton(String text, final OnClickListener listener) {
        configureButton(text, listener, btnNeutral);
        return this;
    }

    private void hideOrShowButtons(boolean show) {
        if (show) {
            if (isAnyVisible(btnCancel, btnNeutral, btnOk)) {
                layoutBtns.setVisibility(View.VISIBLE);
            }
        } else {
            if (isAllGone(btnCancel, btnNeutral, btnOk)) {
                layoutBtns.setVisibility(View.GONE);
            }
        }
    }

    private void configureButton(String text, final OnClickListener listener, Button button) {
        if (listener == null) {
            hideOrShowButtons(false);
            return;
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!listener.onClick(CustomDialog.this)) {
                    dismiss();
                }
            }
        });
        button.setVisibility(View.VISIBLE);
        hideOrShowButtons(true);
        if (!TextUtils.isEmpty(text)) {
            button.setText(text);
        }
        adjustBtnLayout();
    }

    private boolean isAnyVisible(View... views) {
        for (View view : views) {
            if (view.getVisibility() == View.VISIBLE) {
                return true;
            }
        }
        return false;
    }

    private boolean isAllGone(View... views) {
        for (View view : views) {
            if (view.getVisibility() != View.GONE) {
                return false;
            }
        }
        return true;
    }

    private void adjustBtnLayout() {
        boolean isFirst = true;
        for (int i = 0; i < layoutBtns.getChildCount(); i++) {
            View v = layoutBtns.getChildAt(i);
            LayoutParams lp = (LayoutParams) v.getLayoutParams();
            lp.leftMargin = isFirst ? 0 : dip2px(10, getContext());
            v.setLayoutParams(lp);
            isFirst = isFirst && v.getVisibility() == View.GONE;
        }
    }

    /**
     * @see #setCancelable(boolean)
     */
    public CustomDialog setIsCancelable(boolean cancelable) {
        setCancelable(cancelable);
        return this;
    }

    /**
     * @see #setCanceledOnTouchOutside(boolean)
     */
    public CustomDialog setIsCanceledOnTouchOutside(boolean cancel) {
        setCanceledOnTouchOutside(cancel);
        return this;
    }

    public CustomDialog setEnableInput(boolean enableInput) {
        if (enableInput) {
            etInput.setVisibility(View.VISIBLE);
        } else {
            etInput.setVisibility(View.GONE);
        }
        return this;
    }

    public CustomDialog setInputText(String hint, String text) {
        etInput.setText(text);
        etInput.setHint(hint == null ? "" : hint);
        return this;
    }

    public EditText getEditText() {
        return etInput;
    }

    public String getEditTextStr() {
        return etInput.getText() == null ? "" : etInput.getText().toString();
    }

    public CustomDialog showDialog() {
        show();
        return this;
    }

    @Override
    public void show() {
        super.show();
        if (etInput.getVisibility() == View.VISIBLE) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    etInput.requestFocus();
                    showInputKeyboard(getContext(), etInput);
                }
            }, 0);
        }
    }

    public static interface OnClickListener {
        /**
         * @return true 不自动隐藏对话框，false 则自动隐藏
         */
        public boolean onClick(CustomDialog dialog);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue,Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue,Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 显示键盘
     * @param activity
     * @param view
     */
    public static void showInputKeyboard(Context activity, View view) {
        try {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}
